package com.reyco1.services.flickr	
{
	import com.reyco1.core.LoginConstants;
	import com.reyco1.data.Collection;
	import com.reyco1.events.SmartEventDispatcher;
	import com.reyco1.loading.DataLoader;
	
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	import flash.system.LoaderContext;
	
	public class FlickrSearch extends SmartEventDispatcher
	{
		private const PHOTO_SEARCH:String	= "flickr.photos.search";
		
		private var dataLoader:DataLoader;
		private var onComplete:Function;
		private var _photos:Collection;
		private var _currentQuery:String;
		private var _currentPage:Number = 1;
		private var _perPageCount:Number = 100;
		private var _totalPageNumber:Number;
		private var _totalPhotoCount:Number;
		
		public function FlickrSearch(onComplete:Function = null)
		{
			super();
			this.onComplete = onComplete;
		}
		
		public function search(query:String, pageNum:Number = 1, photosPerPage:Number = 100):void
		{
			_currentPage  = pageNum;
			_perPageCount = photosPerPage;
			_currentQuery = query;
			
			var variables:URLVariables  = new URLVariables();
			variables.method			= PHOTO_SEARCH;
			variables.api_key			= LoginConstants.FLICKR_API_KEY;
			variables.text 				= _currentQuery;
			variables.page 				= _currentPage;
			variables.per_page 			= _perPageCount;
			
			var request:URLRequest = new URLRequest(LoginConstants.FLICKR_END_POINT);
			request.data = variables;
			
			dataLoader = new DataLoader(request, {onComplete:handleGotPhotos});
			dataLoader.load();
		}
		
		private function handleGotPhotos(content:Object):void
		{
			_totalPageNumber = XML(content).photos[0].@pages;
			_totalPhotoCount = XML(content).photos[0].@total;
			
			var results:XMLList = XML(content).photos.photo;
			_photos = new Collection();
			
			for(var a:int = 0; a<results.length(); a++)
			{
				var dataItem:FlickrPhotoData = new FlickrPhotoData();
				dataItem.populate(results[a]);
				_photos.addItem(dataItem);
			}
			
			dataLoader.destroy();
			dataLoader = null;
			
			dispatchEvent(new Event(Event.COMPLETE));
			
			if(onComplete != null) onComplete.apply(null, [_photos]);
		}
		
		public function get photos():Collection
		{
			return _photos;
		}
		
		public function get currentQuery():String
		{
			return _currentQuery;
		}
		
		public function get currentPage():Number
		{
			return _currentPage;
		}
		
		public function get perPageCount():Number
		{
			return _perPageCount;
		}
		
		public function get totalPageNumber():Number
		{
			return _totalPageNumber;
		}
		
		public function get totalPhotoCount():Number
		{
			return _totalPhotoCount;
		}
	}
}